﻿using System.Collections.Generic;
using System.Linq;
using DTO;

namespace DAO
{
    public class NgonNguDAO
    {
        public static List<NgonNguDTO> getAll()
        {
            List<NgonNguDTO> result = new List<NgonNguDTO>();
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            var query = dbRaoVat.NGONNGUs.Where(dm => dm.Deleted.Equals(0)).ToList();

            foreach (var ds in query)
            {
                NgonNguDTO dto = new NgonNguDTO();

                dto.MaNgonNgu = ds.MaNgonNgu;
                dto.TenNgonNgu = ds.TenNgonNgu;
                
                result.Add(dto);
            }

            return result;
        }

        public static NgonNguDTO getAlongCode(int maNgonNgu)
        {
            NgonNguDTO result = new NgonNguDTO();
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            var query = dbRaoVat.NGONNGUs.Where(dm => dm.Deleted.Equals(0) &&
                dm.MaNgonNgu == maNgonNgu).Single();

            result.MaNgonNgu = query.MaNgonNgu;
            result.TenNgonNgu = query.TenNgonNgu;

            return result;
        }

        public static void Insert(NgonNguDTO _insert)
        {
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            NGONNGU ngonngu = new NGONNGU();
            ngonngu.TenNgonNgu = _insert.TenNgonNgu;
            ngonngu.Deleted = _insert.Deleted;

            dbRaoVat.NGONNGUs.InsertOnSubmit(ngonngu);
            dbRaoVat.SubmitChanges();
        }

        public static void Delete(int maNgonNgu)
        {
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            NGONNGU _delete = (from n in dbRaoVat.NGONNGUs
                                 where n.MaNgonNgu == maNgonNgu && n.Deleted == 0
                                 select n).Single();

            _delete.Deleted = 1;
            dbRaoVat.SubmitChanges();
        }

        public static void Update(NgonNguDTO dto)
        {
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            NGONNGU _update = (from n in dbRaoVat.NGONNGUs
                               where n.MaNgonNgu == dto.MaNgonNgu && n.Deleted == 0
                               select n).Single();

            _update.TenNgonNgu = dto.TenNgonNgu;
            
            dbRaoVat.SubmitChanges();
        }

        public static int getMa(string tenNgonNgu)
        {
            RaoVatDataContext dbRaoVat = new RaoVatDataContext();

            var query = dbRaoVat.NGONNGUs.Where(dm => 
                dm.TenNgonNgu == tenNgonNgu).Single();

            return query.MaNgonNgu;
        }
    }
}
